import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../utils/date_format_util.dart';
import '../others/common_enum/cell_setting_type.dart';
import '../others/custom_view/setting_items/settting_section.dart';
import '../models/settting_item_model.dart';
import 'controller.dart';
import 'view/mine_vehicle_info_view.dart';
import 'view/order_status_view.dart';
import 'view/user_profile_view.dart';
import 'package:badges/badges.dart' as badges;

// “我的”页面
class MineView extends BaseGetView<MineController> {
  MineView({super.key});

  @override
  MineController get controller => Get.find(tag: AppRoutes.MINE);

  // 是否登录
  final bool _isLoggedIn = GlobalService.to.isLoggedIn;

  @override
  Widget build(BuildContext context) {
    final topHeight = statusBarHeight + navigationBarHeight;
    return VisibilityDetector(
      key: const Key('mine-view-widget-key'),
      onVisibilityChanged: (info) {
        if (info.visibleFraction > 0) {
          // 页面可见时重新加载数据
          controller.reloadPageData();
        }
      },
      child: Material(
        // 铺满全屏幕，避免出现透明区域无法响应点击事件的问题
        child: Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.black,
          child: Stack(
            children: [
              // 背景模糊图片
              Obx(
                () => Container(
                  color: LxCol.theme.withOpacity(0.2),
                  height: screenWidth,
                  child: controller.state.userInfo.value.avatar.isEmpty
                      ? Container(color: LxCol.theme.withOpacity(0.05))
                      : FrostedImage(
                          blurIntensity: 25.0,
                          imagePath: controller.state.userInfo.value.avatar,
                          child: Container(),
                        ),
                ),
              ),
              Column(
                children: [
                  SizedBox(height: screenWidth * 0.6),
                  // 渐变色容器
                  VerticalGradientContainer(
                    colors: _createCurvedGradient(Colors.black),
                    child: Container(height: screenWidth * 0.4),
                  ),
                ],
              ),
              NotificationListener<ScrollNotification>(
                onNotification: (scrollNotification) {
                  if (scrollNotification is ScrollUpdateNotification) {
                    // 实时获取滚动位置
                    controller.state.currentScrollOffset.value =
                        scrollNotification.metrics.pixels;
                  }
                  return false; // 返回 false 允许通知继续传递
                },
                child: // 内容区域
                    SingleChildScrollView(
                  physics: const BouncingScrollPhysics(),
                  child: Obx(() {
                    // 维修
                    final repairItemList = controller.state.itemList
                        .where((element) =>
                            element.sectionType == CellSectionType.repair)
                        .toList();
                    // 查询
                    final inquiryItemList = controller.state.itemList
                        .where((element) =>
                            element.sectionType == CellSectionType.inquiry)
                        .toList();
                    // none
                    final noneItemList = controller.state.itemList
                        .where((element) =>
                            element.sectionType == CellSectionType.none)
                        .toList();
                    // 头像
                    final avatar = controller.state.userInfo.value.avatar;
                    // 昵称
                    final nickname = controller.state.userInfo.value.nickname;
                    // 最新订单提交时间
                    DateTime date = DateFormatUtil.getDate(controller
                        .state.latestOrderInfo.value.submitedTimeStamp.value);
                    return Column(
                      children: [
                        SizedBox(height: topHeight),
                        // 用户信息
                        UserProfileCard(
                          padding: EdgeInsets.only(
                              left: CONTENT_MARGIN * 2,
                              right: CONTENT_MARGIN * 2,
                              top: CONTENT_MARGIN * 2,
                              bottom: CONTENT_MARGIN * 3),
                          avatarSize: 80.w,
                          avatarUrl: _isLoggedIn ? avatar : "",
                          subtitle: _isLoggedIn
                              ? controller
                                      .state.userInfo.value.signature.isEmpty
                                  ? local.enter_signature
                                  : controller.state.userInfo.value.signature
                              : local.enter_signature,
                          nickname:
                              _isLoggedIn ? nickname : local.login_or_register,
                          onTap: () {
                            controller.editUserInfoOnTap();
                          },
                        ),
                        // 车辆信息
                        Padding(
                          padding: EdgeInsets.only(
                            left: CONTENT_MARGIN,
                            right: CONTENT_MARGIN,
                          ),
                          child: SizedBox(
                            width: double.infinity,
                            height: 96.w,
                            child: Obx(
                              () => MineVehicleInfoView(
                                vehicleModelList:
                                    GlobalService.to.cacheVehicleList.toList(),
                                isLogin: _isLoggedIn,
                                onTap: () {
                                  // 跳转车辆列表
                                  controller.vehicleListOnTap();
                                },
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height: CONTENT_MARGIN),

                        // 订单状态卡片
                        Visibility(
                          visible: controller
                              .state.latestOrderInfo.value.id.isNotEmpty,
                          child: OrderStatusCardFlexible(
                            orderMonth: DateFormatUtil.getMonth(date.month),
                            orderDay: date.day.toString(),
                            statusTitle: controller.state.latestOrderInfo.value
                                .orderProgressState.value.title,
                            orderNumber:
                                controller.state.latestOrderInfo.value.id,
                            onTap: () {
                              controller.viewOrderDetailOnTap(
                                  controller.state.latestOrderInfo.value.id);
                            },
                            calendarWidth: 70.w,
                          ),
                        ),

                        // 维修
                        _getCells(repairItemList),
                        // 查询
                        _getCells(inquiryItemList),
                        // none
                        _getCells(noneItemList),
                      ],
                    );
                  }),
                ),
              ),
              // 自定义渐变导航栏
              Obx(() {
                final opacity =
                    (controller.state.currentScrollOffset.value / 50)
                        .clamp(0.0, 1.0);
                return Container(
                  color: Colors.black.withOpacity(opacity),
                  height: topHeight,
                  child: Stack(
                    children: [
                      // 标题
                      Center(
                        child: Container(
                          padding: EdgeInsets.only(top: statusBarHeight),
                          constraints: BoxConstraints(
                            maxWidth: screenWidth -
                                2 * navigationBarHeight -
                                3 * CONTENT_MARGIN,
                          ),
                          child: LxText(
                            local.user_center,
                            color: Colors.white.withOpacity(opacity),
                            fontWeightEnum: LxFontWeightEnum.titleExtraLarge,
                            maxLines: 1,
                          ),
                        ),
                      ),
                      // 消息按钮
                      _messageButton()
                    ],
                  ),
                );
              }),
            ],
          ),
        ),
      ),
    );
  }

  // 消息按钮
  _messageButton() {
    return Padding(
      padding: EdgeInsets.only(top: statusBarHeight),
      child: Container(
        height: navigationBarHeight,
        color: Colors.transparent,
        child: Align(
          alignment: Alignment.centerRight,
          child: IconButton(
            icon: badges.Badge(
              showBadge: false,
              position: badges.BadgePosition.topEnd(top: 0, end: 0),
              badgeStyle: const badges.BadgeStyle(
                padding: EdgeInsets.all(4),
                badgeColor: Colors.red,
              ),
              child: const SizedBox(
                width: 25,
                height: 25,
                child: Icon(
                  Icons.notifications_none_rounded,
                  size: 24,
                ),
              ),
            ),
            onPressed: () {},
          ),
        ),
      ),
    );
  }

  // cell列表
  _getCells(List<SettingSectionModel> itemList) {
    return ListView.builder(
      shrinkWrap: true, // 关键属性
      // 禁止滚动
      physics: const NeverScrollableScrollPhysics(),
      // 消除ListView顶部和底部的间距
      padding: EdgeInsets.only(top: 0, bottom: CONTENT_MARGIN),
      itemCount: itemList.length,
      itemBuilder: (context, sectionIndex) {
        final section = itemList[sectionIndex];
        return SettingSection(
          padding: EdgeInsets.only(
            left: CONTENT_MARGIN,
            right: CONTENT_MARGIN,
            bottom: 0,
            top: 0,
          ),
          isTitleOutside: false,
          title: section.sectionType.name,
          children: section.subItems,
        );
      },
    );
  }

  // 渐变色列表
  List<Color> _createCurvedGradient(Color color) {
    const curve = Curves.easeInOut;
    return [
      color.withOpacity(_getOpacity(0, 5, curve)), // 0.0
      color.withOpacity(_getOpacity(1, 5, curve)), // ~0.08
      color.withOpacity(_getOpacity(2, 5, curve)), // ~0.5
      color.withOpacity(_getOpacity(3, 5, curve)), // ~0.92
      color.withOpacity(_getOpacity(4, 5, curve)), // 1.0
    ];
  }

  double _getOpacity(int index, int total, Curve curve) {
    double progress = index / (total - 1);
    return curve.transform(progress);
  }
}
